package cn.zhaoyuening.zamh.looper;

import cn.zhaoyuening.zamh.handler.MsgHandler;
import cn.zhaoyuening.zamh.msg.Msg;
import cn.zhaoyuening.zamh.queue.MsgQueue;

import java.util.List;
import java.util.Map;

/**
 * Created by 赵岳宁 on 2017/6/3.
 */
public class BaseLooper implements MsgLooper {
    private MsgQueue queue;
    private Map<Integer, List<MsgHandler>> msgMap ;

    public void loop() {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    if (queue.size()==0){
                        synchronized (queue){
                            try {
                                queue.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                        continue;
                    }
                    Msg msg = queue.pop();
                    int msgId = msg.getId();
                    List<MsgHandler> handlers = msgMap.get(msgId);
                    if (handlers == null) {
                        System.err.println("消息ID:"+msgId+" 未注册MsgHandler");
                        continue;
                    }
                    for (MsgHandler handler :
                            handlers) {
                        handler.handle(msg);
                    }
                }
            }
        }).start();
    }

    public void setQueue(MsgQueue queue) {
        this.queue = queue;
    }

    public void setMsgMap(Map<Integer, List<MsgHandler>> msgMap) {
        this.msgMap = msgMap;
    }
}
